/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package give.replay;

import give.comm.handling.MessageHandlingThread;
import give.replay.gui.AbstractMain;
import give.replay.gui.ReplayControlForm;
import give.world.World;
import java.sql.SQLException;

/**
 *
 * @author koller
 */
public class ReplayApplication extends AbstractMain {
    private World world, worldBackup;
    private GameEventReplayer replayer;
    private DatabaseGameLogSource source;
    private ReplayControlForm controlFrame;
    private MessageHandlingThread handler;
    private ReplayWindow replayWindow;

    public ReplayApplication(String configFile, ReplayWindow replayWindow) throws SQLException {
        super(configFile);

        source = new DatabaseGameLogSource(config.getDb().getDatabaseConnection());
        replayer = new GameEventReplayer();
        this.replayWindow = replayWindow;
        dbSelectionInterface = null;

        controlFrame = new ReplayControlForm(replayer, this);
        controlFrame.setVisible(true);
    }

    @Override
    public void openMap(int gameid) {

        try {
            // load world
            String worldName = source.getWorldName(gameid);
            World originalWorld = config.getWorldManager().getWorldForName(worldName);

            if (originalWorld == null) {
                displayError("Couldn't find world " + worldName);
                return;
            }

            world = (World) originalWorld.clone();
            worldBackup = (World) world.clone();

            replayWindow.openReplayWindow(world, "Game Replay: " + gameid, config.getDb().getClientMetadata(gameid));

            // set up replayer and reinitialize replay controller
            handler = new MessageHandlingThread(world, replayWindow);
            handler.start();

            replayer.clear();
            replayer.addAll(source.getEvents(gameid, world));
            replayer.replay(handler, false);

            controlFrame.setPlayPauseButtonState(GameEventReplayer.State.PAUSED);
            controlFrame.populateEventList();
        } catch (SQLException ex) {
            displayError("SQL exception: " + ex.getMessage());
        }
    }

    private void displayError(String error) {
        System.err.println("*** ERROR: " + error + " ***");
    }


    @Override
    public void jumpTo(int eventIndex) {
        if (eventIndex <= replayer.getCurrentEventIndex()) {
            handler.interrupt();

            worldBackup.copyTo(world);
            replayWindow.synchronizeWorld();

            handler = new MessageHandlingThread(world, replayWindow);
            handler.start();

            replayer.replay(handler, false);
        }

        replayer.jumpTo(eventIndex);
    }
}
